/*
 * @lc app=leetcode.cn id=64 lang=javascript
 *
 * [64] 最小路径和
 */

// @lc code=start
/**
 * @param {number[][]} grid
 * @return {number}
 */
var minPathSum = function (grid) {
  const m = grid.length; //行数
  const n = grid[0].length; //列数
  // 注意这样创建的数组不会导致子数组是同一个引用对象
  const curMin = Array.from({ length: m }, () => new Array(n).fill(0));
  curMin[0][0] = grid[0][0];
  for (let i = 1; i < m; i++) curMin[i][0] = curMin[i - 1][0] + grid[i][0];
  for (let j = 1; j < n; j++) curMin[0][j] = curMin[0][j - 1] + grid[0][j];
  for (let i = 1; i < m; i++) {
    for (let j = 1; j < n; j++) {
      curMin[i][j] = Math.min(curMin[i - 1][j], curMin[i][j - 1]) + grid[i][j];
    }
  }
  return curMin[m - 1][n - 1];
};
// @lc code=end
